<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/1 9:35
 * Modified Time: 2019/7/1 9:35
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Exceptions\NotFoundException;
use App\Lib\Auth\FLAuth;
use App\Lib\Utilities;
use App\Modules\MemberCard\Criterias\AppGetCardTypeListCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeAppCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeByIdCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeNumCriteria;
use App\Modules\MemberCard\Criterias\GetCardTypeServiceCriteria;
use App\Modules\MemberCard\Repositores\CardTypeRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Service\Repositories\CardTypeServiceRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use mysql_xdevapi\Exception;

class CardTypeService extends BaseService
{
    private $FLAuth;
    private $cardTypeRepository;
    private $serviceRepository;
    private $userStoreRepository;
    private $memberCardRepository;
    private $cardTypeServiceRepository;

    public function __construct(CardTypeRepository $cardTypeRepository,
                                UserStoreRepository $userStoreRepository,
                                ServiceRepository $serviceRepository,
                                CardTypeServiceRepository $cardTypeServiceRepository,
                                MemberCardRepository $memberCardRepository,
                                FLAuth $FLAuth)
    {
        $this->FLAuth = $FLAuth;
        $this->cardTypeRepository = $cardTypeRepository;
        $this->userStoreRepository = $userStoreRepository;
        $this->serviceRepository = $serviceRepository;
        $this->memberCardRepository = $memberCardRepository;
        $this->cardTypeServiceRepository = $cardTypeServiceRepository;
    }

    /**
     * 新增会员卡类
     * @param $store_id
     * @param $category
     * @param $price
     * @param $name
     * @param $present
     * @param $count
     * @param $royalty
     * @param $service
     * @return mixed
     * @throws AllValidatorException
     */
    public function createCardType($store_id, $category, $price, $name, $present, $count, $royalty, $service_data, $discount_way, $skin,$is_general,$assist_royalty)
    {
        DB::beginTransaction();
        try {

            if ($category == 1) {
//                $service = json_decode($service_data, true);
//                $service_id = 0;
//                foreach ($service as $key => $value) {
//                    //判断服务是否存在
//                    $this->checkServiceExist($value['service_id'], $store_id);
//                    $service_id = $value['service_id'];
//                }
//                $service = $this->serviceRepository->find($service_id);

                $unit_price = $price / $count;
            } else {
                $unit_price = 0;
            }
            //创建会员卡类
            $card_type = $this->cardTypeRepository->createCardType($store_id, $category, $price, $name, $present, $count, $royalty, $discount_way, $skin, $unit_price,$is_general,$assist_royalty);

            if(!$is_general){ //如果不是通用卡 绑定服务
                $this->bindService($service_data, $card_type);
            }

            DB::commit();
            return $card_type;
        } catch (AllValidatorException $allValidatorException) {
            DB::rollBack();
            throw new AllValidatorException(['msg' => $allValidatorException->msg]);
        }

    }

    /**
     * 编辑会员卡类
     * @param $store_id
     * @param $category
     * @param $price
     * @param $name
     * @param $present
     * @param $count
     * @param $royalty
     * @param $service
     * @return mixed
     * @throws AllValidatorException
     */
    public function editCardType($card_type_id, $category, $price, $name, $present, $count, $royalty, $service_data, $discount_way, $skin,$is_general,$assist_royalty)
    {
        $member_card_count = $this->memberCardRepository->getCardTypeCount($card_type_id);
        if ($member_card_count > 0) {
            throw new AllValidatorException(['msg' => '该卡类已有用户办理不可编辑']);
        }

        $card_type = $this->cardTypeRepository->find($card_type_id);
        if ($category === null) {
            $category = $card_type->category;
        }
        if ($price === null) {
            $price = $card_type->price;
        }

        //如果是次数卡 判断改没改服务或次数 修改服务单价
        if ($category == 1) {
//            if ($service_data !== null) {
////                $service = json_decode($service_data, true);
////                $service_id = 0;
////                foreach ($service as $key => $value) {
////                    $service_id = $value['service_id'];
////                }
////            } else {
////                $service_id = $this->cardTypeServiceRepository
////                    ->findByField(['type_id' => $card_type_id])
////                    ->first()
////                    ->service_id;
////            }
////
////            $service = $this->serviceRepository->find($service_id);
////            if ($count === null) {
////                $count = $card_type->count;
////            }
           $unit_price = $price / $count;


        } else {
            $unit_price = 0;
        }

        DB::beginTransaction();
        try {


            $card_type = $this->cardTypeRepository->editCardType($card_type_id, $category, $price, $name, $present, $count, $royalty, $discount_way, $skin, $unit_price,$is_general,$assist_royalty);

            if($is_general){ //通用卡
                //删除之前的
                $this->cardTypeServiceRepository->deleteByCardTypeId($card_type->id);
            }else{
                if ($service_data) {
                    //绑定服务
                    $this->bindService($service_data, $card_type, 1);
                }
            }

            DB::commit();
            return $card_type;
        } catch (Exception $exception) {
            DB::rollBack();
            throw new DbException();
        }

    }

    /**
     * 删除会员卡
     * @param $card_type_id
     * @throws AllValidatorException
     * @throws DbException
     */
    public function delCardType($card_type_id)
    {
        $member_card_count = $this->memberCardRepository->getCardTypeCount($card_type_id);
        if ($member_card_count > 0) {
            throw new AllValidatorException(['msg' => '该卡类已有用户办理不可删除']);
        }
        DB::beginTransaction();
        try {
            $this->cardTypeRepository->delete($card_type_id);
            $this->cardTypeServiceRepository->deleteByCardTypeId($card_type_id);
            return DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new DbException();
        }

    }

    /**
     * 开关会员卡类
     * @param $card_type_id
     * @param $status
     * @return mixed
     */
    public function switchCardType($card_type_id, $status)
    {
        return $this->cardTypeRepository->switchCardType($card_type_id, $status);
    }

    /*
     * 获取本店所有卡类 分页
     */
    public function getCardTypeListPage($store_id, $status, $keywords, $pageSize)
    {
        $card_type_listpage = $this->cardTypeRepository->pushCriteria(new AppGetCardTypeListCriteria($store_id, $status, $keywords))->paginate($pageSize, ['*'], 'paginate');

        $card_type_listpage = Utilities::dealPage($card_type_listpage);
        return $card_type_listpage;

    }

    /**
     * 获取本店所有会员卡数
     * @param $store_id
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getCardTypeNum($store_id)
    {
        return $this->cardTypeRepository->pushCriteria(new GetCardTypeNumCriteria($store_id))->first();
    }

    /**
     * @param $requestData
     * @return mixed
     * @throws NotFoundException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getCardTypeService($card_type_id)
    {
        return $this
            ->cardTypeServiceRepository
            ->pushCriteria(new GetCardTypeServiceCriteria($card_type_id))
            ->get();
    }


    /*
     * 根据会员卡类id获取会员卡信息
     */
    public function getCardType($card_type_id)
    {
        $card_type = $this->cardTypeRepository->pushCriteria(new GetCardTypeByIdCriteria($card_type_id))->first();

        if (!$card_type) {
            throw new NotFoundException(['msg' => '没有找到该卡类']);
        }

        return $card_type;
    }

    /*
     * 根据会员卡类id获取会员卡信息 App
     */
    public function getCardTypeApp($card_type_id)
    {
        $card_type = $this->cardTypeRepository->pushCriteria(new GetCardTypeAppCriteria($card_type_id))->first();

        if (!$card_type) {
            throw new NotFoundException(['msg' => '没有找到该卡类']);
        }

        return $card_type;
    }

    /*
     * 绑定服务
     */
    private function bindService($service, $card_type, $is_edit = 0)
    {


        if ($is_edit) {
            //判断有没有减少服务
            $card_type_service = $this->cardTypeServiceRepository->findByField(['type_id' => $card_type->id])->toArray();
//            $card_type_service = collect($card_type_service);
            $old_service_list = [];
            $new_service_list = [];
            foreach ($card_type_service as $key => $value) {
                $old_service_list[] = $value['service_id'];
            }
//            dd($old_service_list);
            $service = json_decode($service, true);
            foreach ($service as $key => $value) {
                $new_service_list[] = $value['service_id'];
            }
            $diff = array_diff($old_service_list, $new_service_list);

            if (count($diff) > 0) {
                throw new AllValidatorException(['msg' => '已办出的卡类不支持减少适用服务哦']);
            }

            //删除之前的
            $this->cardTypeServiceRepository->deleteByCardTypeId($card_type->id);
        } else {
            $service = json_decode($service, true);
        }


        if (count($service) == 0) {
            throw new AllValidatorException(['msg' => '请选择适用服务']);
        }
        $store_id = $card_type->store_id;
        foreach ($service as $key => $value) {
            //判断服务是否存在
            $this->checkServiceExist($value['service_id'], $store_id);

            //创建关联
            if ($card_type->category == 2) {
                if (isset($value['discount'])) {
                    $discount = $value['discount'] * config('constant.discountRate');
                    if ($discount == 0 || $discount == '') {//未填折扣
                        $discount = 100;
                    }
                } else {
                    $discount = 100;
                }

            } else {
                $discount = 100;
            }
            $data = [
                'type_id' => $card_type->id,
                'service_id' => $value['service_id'],
                'discount' => $discount
            ];
            $this->cardTypeServiceRepository->create($data);
        }

    }

    /*
     * 判断服务是否存在
     */
    private function checkServiceExist($service_id, $store_id)
    {
        $service_num = $this->serviceRepository->findByField(['id' => $service_id, 'store_id' => $store_id])->count();

        if ($service_num == 0) {
            throw new NotFoundException(['msg' => '服务不存在']);
        }
    }

}